import {Coverage, TestParser} from '../../test-parser'
import * as step from '@flow-step/step-toolkit'
import {checkCoverageFileExist} from '../../utils'
import {readFile} from '../../utils'

export class MochaParser implements TestParser {
    async coverageFile(path: string): Promise<string> {
        if (!path.endsWith('.html')) {
            throw new Error(`Input variable 'reportPath' should reference a report with html extension`)
        }

        const coverageFile = path.replace('.html', '.json')
        await checkCoverageFileExist(coverageFile)
        return coverageFile
    }

    htmlFile(path: string): string {
        return path
    }

    async parse(path: string): Promise<Coverage> {
        step.info(`Parsing Mocha Json report: ${path}`)
        const jsonFile = await readFile(path)
        return this.count(jsonFile)
    }

     count (jsonFile: string) {
        const jsonContent = JSON.parse(jsonFile)
        const coverage = {
            total: jsonContent.stats.tests,
            passed: jsonContent.stats.passes,
            failed: jsonContent.stats.failures,
            skipped: jsonContent.stats.pending,
            passedRate: Math.round(jsonContent.stats.passPercent*100)/100
        } as Coverage

        return coverage
    }
}